package com.example.demo_news.service.User;

import java.util.Date;
import java.util.List;

import com.example.demo_news.Repository.PersonRepository;
import com.example.demo_news.Repository.UserPepository;
import com.example.demo_news.entity.Person;
import com.example.demo_news.entity.MyUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @Autowired
    private UserPepository userPepository;
    @Autowired
    private PersonRepository personRepository;

    public MyUser findUserById(Integer id) {
        return userPepository.findUserById(id);
    }

    public boolean save(MyUser user) {
        try {
            if (userPepository.findUserByusername(user.getUsername()) == null)            {
                Person person = new Person();
                Date date = new Date();
                person.setCreationDate(date);
                personRepository.save(person);
                user.setPerson(person);
                userPepository.save(user);
                // 保存用户和个人信息
                return true;
            } else
                return false;
        } catch (Exception e) {
            return false;
        }
    }

    public List<MyUser> findAll() {
        return userPepository.findAll();
    }

    public MyUser findByUsername(String username) {
        return userPepository.findUserByusername(username);
    }
}
